package net.jxvtc.eshop.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import net.jxvtc.eshop.domain.User;
import net.jxvtc.eshop.utils.DataSourceUtils;

/**
 * 用户DAO类
 * @author Administrator
 *
 */
public class UserDao {

	/**
	 * 功能：添加新用户
	 * @param user 用户实体类对象
	 * @throws SQLException 
	 */
	public void addUser(User user) throws SQLException
	{
		String sql = "insert into user(username,password,gender,"
				+ "email,telephone,introduce,activecode) "
				+ "values(?,?,?,?,?,?,?)";
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		int row = runner.update(sql, user.getUsername(), user.getPassword(),
				user.getGender(), user.getEmail(), user.getTelephone(),
				user.getIntroduce(), user.getActiveCode());
		System.out.println(row);
		if (row == 0) {
			throw new RuntimeException();
		}
	}
	/**
	 * 功能：根据激活码查找用户
	 * @param activeCode
	 * @return
	 * @throws SQLException
	 */
	public User findUserByActiveCode(String activeCode) throws SQLException
	{
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		User user=runner.query("select * from `user` where activeCode=?", 
				new BeanHandler<User>(User.class),activeCode);
		return user;
	}
	
	
	// 激活用戶
		public void activeUser(String activeCode) throws SQLException {
			String sql = "update user set state=? where activecode=?";
			QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
			runner.update(sql, 1, activeCode);
		}
		public User findUserByUsernameAndPassword(String username, String password) throws SQLException {
			String sql="select * from user where username=? and password=?";
			QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
			return runner.query(sql, new BeanHandler<User>(User.class),username,password);
		}
	
}